package cn.nexd.app.collector.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;

import cn.nexd.app.collector.Configuration;
import cn.nexd.app.collector.R;
import cn.nexd.app.collector.model.FloorLayer;
import cn.nexd.app.collector.presenter.settinglocation.SettingLocationContract;
import cn.nexd.app.collector.presenter.settinglocation.SettingLocationPresenter;
import cn.nexd.app.collector.util.UMengUtil;
import cn.nexd.utils.framework.error.NexdCrashException;
import cn.nexd.utils.framework.tools.FileUtil;
import cn.nexd.utils.framework.tools.Logger;

public class SettingLocationActivity extends AppCompatActivity implements SettingLocationContract.View, View.OnClickListener, Spinner.OnItemSelectedListener {


    private static final String TAG = "SettingLocationActivity";

    private String buildingName;
    private String buildingId;
    private RadioButton checkWifi;
    private EditText etFloorId;
    private String str_locationInterval = "";
    private String str_dataBuffer = "";

    private SettingLocationContract.Presenter presenter;
    private InputMethodManager inputMethodManager;
    private ArrayList<FloorLayer> floorLayers;
    private CheckBox autoChange;

    private ProgressDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting_location);
        initView();
        presenter = new SettingLocationPresenter(this, this);
    }


    @Override
    protected void onResume() {
        super.onResume();
        UMengUtil.getInstance().onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (inputMethodManager.isActive()) {
            inputMethodManager.hideSoftInputFromWindow(etFloorId.getWindowToken(), 0);
        }
        UMengUtil.getInstance().onPause(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button:

                presenter.checkPermission();
                break;
            case R.id.auto_change:


                break;
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void initView() {
        hideToolbar();
        initInput();
        initProgressDialog();

        Intent intent = getIntent();
        buildingName = intent.getStringExtra("buildingName");
        buildingId = intent.getStringExtra("buildingId");
        floorLayers = intent.getParcelableArrayListExtra("floors");
        autoChange = (CheckBox) findViewById(R.id.auto_change);
//        autoChange.setOnClickListener(this);
        TextView tvBuildingName = (TextView) findViewById(R.id.mall_name);

        tvBuildingName.setText(buildingName + "\n" + buildingId);
        checkWifi = (RadioButton) findViewById(R.id.checkWifi);
        RadioButton checkBlue = (RadioButton) findViewById(R.id.checkBlue);
        Button startTest = (Button) findViewById(R.id.button);
        startTest.setOnClickListener(this);

        if (floorLayers != null && floorLayers.size() == 0) {
            startTest.setClickable(false);
            Toast.makeText(this, "未找到楼层信息！\n联网更新数据，或联系地图管理员！", Toast.LENGTH_SHORT).show();
        }
        etFloorId = (EditText) findViewById(R.id.floor_id);
        etFloorId.setText(buildingId);

        Spinner locationInterval = (Spinner) findViewById(R.id.locationInterval);
        Spinner dataBuffer = (Spinner) findViewById(R.id.buffer);

        ArrayAdapter<CharSequence> locationInterValAdapter = ArrayAdapter.createFromResource(this, R.array.locationInterval, android.R.layout.simple_list_item_1);
        ArrayAdapter<CharSequence> dataBufferAdapter = ArrayAdapter.createFromResource(this, R.array.data_buffer, android.R.layout.simple_list_item_1);

        dataBufferAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        locationInterValAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);

        locationInterval.setPopupBackgroundResource(R.color.cpb_white);
        dataBuffer.setPopupBackgroundResource(R.color.cpb_white);

        dataBuffer.setAdapter(dataBufferAdapter);
        locationInterval.setAdapter(locationInterValAdapter);


        locationInterval.setOnItemSelectedListener(this);
        dataBuffer.setOnItemSelectedListener(this);

        locationInterval.setSelection(0);
        dataBuffer.setSelection(0);
    }

    private void initProgressDialog() {
        loadingDialog = new ProgressDialog(this);
        loadingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        loadingDialog.setMessage("数据下载中...");
    }

    private void initInput() {
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            hideToolbar();
        }
    }

    private void hideToolbar() {
        View mDecorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            mDecorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mDecorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        getSupportActionBar().hide();
    }

    @Override
    public void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void startActivity() {
        Intent intent = new Intent(SettingLocationActivity.this, NexdMapActivity.class);
        intent.putExtra("buildingName", buildingName);
        intent.putExtra("buildingId", buildingId);
        // 传递楼层信息，到地图层
        intent.putParcelableArrayListExtra("floors", floorLayers);
        if (checkWifi.isChecked()) {
            intent.putExtra("model", "wifi");
        } else {
            intent.putExtra("model", "blue");
        }
        intent.putExtra("autoChange", autoChange.isChecked());
        intent.putExtra("interval", "".equals(str_locationInterval) ? "1000" : str_locationInterval);
        intent.putExtra("buffer", "".equals(str_dataBuffer) ? "3000" : str_dataBuffer);
        startActivity(intent);
        SettingLocationActivity.this.finish();
    }

    @Override
    public void printLog(String msg) {
        Log.d(TAG, "printLog: " + msg);
    }

    public void onClick_back(View view) {
        this.finish();
    }

    @Override
    protected void onStop() {
        super.onStop();
        destroyDialog();
        if (inputMethodManager.isActive()) {
            inputMethodManager.hideSoftInputFromWindow(etFloorId.getWindowToken(), 0);
        }
    }

    @Override
    public void showDownDialog() {
        try {
            if (FileUtil.checkExist(Configuration.getSavePath(Configuration.Path.LOCATION_BASE_PATH) + buildingId + "/")) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setCancelable(false).setMessage("检测到本地存在配置文件，请确认是否为最新，确认请点击\"确认\"，否则点击\"下载\"")
                        .setNegativeButton("下载", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Log.d(TAG, "onClick: Download");

                                presenter.requestUrl(buildingId);
                            }
                        })
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                startActivity();
                            }
                        }).show();
            } else {
                Logger.debug(TAG, "showDownDialog: 未检测到文件，请求下载");
                presenter.requestUrl(buildingId);
            }
        } catch (IOException e) {
            e.printStackTrace();
            UMengUtil.getInstance().reportError(this, e);
            NexdCrashException.getInstance().reportException(e);
        }
    }


    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

        switch (adapterView.getId()) {
            case R.id.locationInterval:

                str_locationInterval = adapterView.getItemAtPosition(i).toString();
                break;

            case R.id.buffer:

                str_dataBuffer = adapterView.getItemAtPosition(i).toString();
                break;
        }

    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }

    @Override
    public void showLoadingDialog() {
        loadingDialog.show();
    }

    @Override
    public void dismissLoadingDialog() {
        loadingDialog.dismiss();
    }


    @Override
    protected void onDestroy() {
        destroyDialog();
        super.onDestroy();
    }

    private void destroyDialog() {
        if (loadingDialog.isShowing()) {
            loadingDialog.dismiss();
            if (loadingDialog != null) {
                loadingDialog = null;
            }
        }
    }
}
